//
//  DFPlaceholderTextView.swift
//  FlyBlog
//
//  Created by FEI on 16/4/19.
//  Copyright © 2016年 FEI. All rights reserved.
//

import UIKit

class DFPlaceholderTextView: UITextView {

    var placeholder: String? {
        didSet {
            placeholderLabel.text = placeholder
        }
    }

    override var text: String! {
        didSet {
            placeholderLabel.hidden = self.hasText()
        }
    }

    override var font : UIFont? {
        didSet {
            placeholderLabel.font = font
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)

        prepareUI()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didChangeText"), name: UITextViewTextDidChangeNotification, object: self)
    }

    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    @objc private func didChangeText() {
        placeholderLabel.hidden = hasText()
    }

    private func prepareUI(){
        self.addSubview(placeholderLabel)

        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))

    }


    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        label.font = self.font
        label.textColor = UIColor.lightGrayColor()
        label.text = "分享新鲜事..."
        label.sizeToFit()
        return label
    }()

}
